package com.paic.mario.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paic.mario.domain.ContentObject;
import com.paic.mario.domain.DownProObject;
import com.paic.mario.domain.ServiceTempletVo;
import com.paic.mario.service.SystemService;
import com.paic.mario.service.TempletService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



@RestController
public class SystemController {

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private TempletService templetService;
	
	@RequestMapping(value="/system/getSystem",method=RequestMethod.GET)
	public  List<Map<String, Object>> getSystemBySeriesId(@RequestParam(value="series_id", required=true) int series_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getSystemBySeriesId(series_id);
		return reslutList;
	}
	
	//获取系统下的所有信息
	@RequestMapping(value="/system/getAllObject",method=RequestMethod.GET)
	public  List<Map<String, Object>> getAllObjectBySystemId(@RequestParam(value="system_id", required=true) int system_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getObjectBySystemId(system_id);
		return reslutList;
	}
	
	//获取系统下的应用信息
	@RequestMapping(value="/system/getAppObject",method=RequestMethod.GET)
	public  List<Map<String, Object>> getAppObjectBySystemId(@RequestParam(value="system_id", required=true) int system_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getAppObjectBySystemId(system_id);
		return reslutList;
	}
	
	//获取应用下所有服务
	@RequestMapping(value="/system/getServiceObject",method=RequestMethod.GET)
	public  List<Map<String, Object>> getServiceObjectByAppId(@RequestParam(value="app_id", required=true) int app_id){ 
		List<Map<String, Object>> reslutList_app = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> reslutList_service = new ArrayList<Map<String, Object>>();
		reslutList_app = systemService.getServiceObjectByAppId(app_id);
		
		for(Map map:reslutList_app){
			reslutList_service = systemService.getServiceByObjectId(Integer.parseInt(map.get("obj_id").toString()));
		    if(reslutList_service.size()>0){
		    	map.put("host_name", reslutList_service.get(0).get("host_name"));
		    }
		}

		return reslutList_app;
	}

	//获取单个服务，通过service_id
	@RequestMapping(value="/system/getService",method=RequestMethod.GET)
	public  List<Map<String, Object>> getServiceByObjectId(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> propertiesList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getServiceByObjectId(object_id);
		//获取服务对应的主机信息和IP
		for(int t=0 ; t< reslutList.size(); t++){
			String host_name = reslutList.get(t).get("host_name").toString();
			Map obj_map = new HashMap();
			obj_map.put("host_name", host_name);
			propertiesList = systemService.getHostPropertiesByHostName(obj_map);
			
			if(propertiesList.size()==0){
				return reslutList;
			}
			String hostName = "";
			String ip = "";
			for(int o = 0;o <propertiesList.size(); o++){
				if(propertiesList.get(o).containsKey("property_name")){
				if("hostName".equals(propertiesList.get(o).get("property_name"))){
					hostName = propertiesList.get(o).get("property_value").toString();
				}
				if("ip".equals(propertiesList.get(o).get("property_name"))){
					ip = propertiesList.get(o).get("property_value").toString();
				}
				}
			}
			obj_map.put("ip", ip);
			obj_map.put("hostName", hostName);
			((Map)reslutList.get(t)).put("ip", ip);
			((Map)reslutList.get(t)).put("hostName", hostName);
		}

		return reslutList;
	}
	
	@RequestMapping(value="/system/getTemplet",method=RequestMethod.GET)
	public  List<Map<String, Object>> getTempletByObjectId(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getTempletByObjectId(object_id);
		return reslutList; 
	}
	
	/**
	 * 获取可配置的模板，通过ser_id
	 * @param service_list
	 * @return
	 */
	@RequestMapping(value="/system/getTemplet",method=RequestMethod.POST)
	public  List<Map<String, Object>> getTempletByObjectIds(@RequestBody List<Integer> object_ids){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		if(object_ids.size()>0){
			reslutList = systemService.getTempletByObjectIds(object_ids);
		}
		return reslutList; 
	}
	
	/**
	 * 获取已选模板接口
	 * @param service_list
	 * @return
	 */
	@RequestMapping(value="/system/getSelectedTemplet",method=RequestMethod.GET)
	public  List<Map<String, Object>> getSelectedTemplet(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		reslutList = systemService.getSelectedTempletByObjectId(object_id);
		return reslutList; 
	}
	
	/**
	 * add下发接口
	 * @param service_list
	 * @return
	 */
	@RequestMapping(value="/system/addServiceTemplet",method=RequestMethod.POST)
	public  int addServiceTemplet(@RequestBody List<Map> service_list ){ 
         int cnt = 0;
         List<ServiceTempletVo> addservice_list = new ArrayList<ServiceTempletVo>();
         
         int templet_id = (int)service_list.get(0).get("templet_id");
         String content = systemService.getTempContent(templet_id);
         for(Map map : service_list){
        	 List<Map<String,Object>> list_properties = (List<Map<String, Object>>) map.get("templet_properties");
        	 //Map<String,Object>  cmap = changMap(list_properties);
        	 JSONArray json = JSONArray.fromObject(list_properties);
        	 //map.put("json_text", json.toString());
        	 
    		 Map map_properties_key = new HashMap();
        	 for(Map key_map:list_properties){ 
        		 map_properties_key.put(key_map.get("key_ena").toString(), key_map.get("defult_value"));
        	 }
    	 
        	 //map_properties_key:真实值;content:格式值
        	 String Value = changeValueJson(map_properties_key,content);
        	 map.put("json_text", Value); //插入记录的json_text
        	       	 
        	 //落库
        	 //只能一个一个服务一个服务的入库
        	 ServiceTempletVo insert_Vo =new ServiceTempletVo();
        	 insert_Vo.setObj_id(map.get("obj_id").toString());
        	 insert_Vo.setTemplet_id(map.get("templet_id").toString());
        	 insert_Vo.setHost_name(map.get("host_name").toString());
        	 insert_Vo.setJson_text(Value);
        	 Map insert_map = systemService.addOneServiceTemplet(insert_Vo);	 
        	 cnt += Integer.parseInt(insert_map.get("cnt").toString());
      	     String down_id = insert_map.get("id").toString();
        	 
        	 //根据上面落库，生成下发的信息,必须有的三个参数,filename,indextemplateid,host_name
        	 map.put("file_name", map.get("service_id").toString() + templet_id + down_id);
        	 map.put("indextemplateid", map.get("service_id").toString() + templet_id + down_id);
        	 map.put("id", down_id);
        	 //回写这个文件名to配置表库中
        	 
        	 int update_indextemplateid_count = systemService.updateOneServiceIndextemplateid(map);
        	 
        	 //调用生成下发content的方法
        	 String Properties = changeValueProperties(map,map_properties_key,content);
             map.put("content",Properties);   //下发需要的content        	 
         }
         
         //down_cnt = systemService.addServiceTemplet(service_list);
         String flag = "add";
	     //String host_name = service_json_list.get(i).get("host_name").toString();
	     //String service_id = service_json_list.get(i).get("service_id").toString();				
	     //String param = service_json_list.get(i).get("content").toString();
         //test
         //下发
         templetService.saveAndloadTemplet(templet_id, flag ,service_list);
        
         return cnt;
	}
	
	public Map<String,Object> changMap(List<Map<String,Object>> list){
		Map<String,Object> map = new HashMap<String,Object>();
	    for(Map<String,Object> imap : list){
	    	map.put(imap.get("key_ena").toString(), imap.get("defult_value"));
	    }
	    return map;
	}
	
	/**
	 * 格式内容替换转化json,保存库中
	 * @param map
	 * @param content
	 * @return
	 */
	public String changeValueJson(Map<String,Object> map,String content){
		String Value = "";
		//content未替换格式
		ContentObject contentObject = new Gson().fromJson(content, new TypeToken<ContentObject>() {}.getType());
		String frequency = contentObject.getFrequency();
		String[] fre = frequency.split(",");
		if(map.containsKey("frequency")){
			frequency.replaceAll(fre[1],map.get("frequency").toString());
			contentObject.setFrequency(frequency);
		}
		//config
		Map<String,Object> config = contentObject.getConfig();
		Set<String> keys =config.keySet();
		for(String key :keys){
            //非嵌套
			if(!"contentfilter".equals(key) && !"match".equals(key)){
				String value = config.get(key).toString();
				//String[] value_array = value.split(",");
				String[] value_array = commaDivider(value);
				//if("sqls".equals(key)||"successflag".equals(key)||"msqls".equals(key)||"logfiles".equals(key)){
				if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)){
					value_array[1] ="\"["+map.get(key).toString()+"]\"";
				}else{
					value_array[1] = map.get(key).toString();
				}
				
				String  value_array_str=StringUtils.join(value_array, ",");
				config.put(key, value_array_str);
			//contentfilter嵌套
			}else if("contentfilter".equals(key)){
				Map <String, Object>  contentfilterJsonTextMap = new HashMap<String, Object>();
				Map <String, Object>  contentfilterMap= (Map) config.get(key);
				
				Set<String> contentfilterkeys =contentfilterMap.keySet();
				for(String contentfilterkey :contentfilterkeys){
					String value = contentfilterMap.get(contentfilterkey).toString();
					//String[] value_array = value.split(",");
					String[] value_array = commaDivider(value);
					if("successflag".equals(contentfilterkey)){
						value_array[1] ="\"["+map.get(contentfilterkey).toString()+"]\"";
					}else if("columns".equals(contentfilterkey)||"urlstaticdef".equals(contentfilterkey)||"columnsreg".equals(contentfilterkey)){
						value_array[1] ="\""+map.get(contentfilterkey).toString()+"\"";
					}else{
						value_array[1] = map.get(contentfilterkey).toString();
					}
					if(value_array.length==4){
						value_array[3] = "\""+value_array[3]+"\"";
					}

					
					String  value_array_str=StringUtils.join(value_array, ",");
					contentfilterJsonTextMap.put(contentfilterkey, value_array_str);
				}
				config.put(key, contentfilterJsonTextMap);
			}else if("match".equals(key)  && "javagclog".equals(contentObject.getType())){
				Map <String, Object>  contentfilterJsonTextMap = new HashMap<String, Object>();
				Map <String, Object>  contentfilterMap= (Map) config.get(key);
				
				Set<String> contentfilterkeys =contentfilterMap.keySet();
				for(String contentfilterkey :contentfilterkeys){
					String value = contentfilterMap.get(contentfilterkey).toString();
					//String[] value_array = value.split(",");
					//String[] value_array = commaDivider(value);
					String[] value_array = value.split(",");
					if("oc".equals(contentfilterkey) || "yc".equals(contentfilterkey)){
						//String tempC = map.get(contentfilterkey).toString();
						value_array[1] = "\"" +map.get(contentfilterkey).toString() +"\"" ;
					}
				
					String  value_array_str=StringUtils.join(value_array, ",");
					contentfilterJsonTextMap.put(contentfilterkey, value_array_str);
				}
				config.put(key, contentfilterJsonTextMap);
			}else{
				String value = config.get(key).toString();
				//String[] value_array = value.split(",");
				String[] value_array = commaDivider(value);
				//if("sqls".equals(key)||"successflag".equals(key)||"msqls".equals(key)||"logfiles".equals(key)){
				if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)){
					value_array[1] ="\"["+map.get(key).toString()+"]\"";
				}else{
					value_array[1] = map.get(key).toString();
				}
				
				String  value_array_str=StringUtils.join(value_array, ",");
				config.put(key, value_array_str);
			}
	
		}
		
		JSONObject json = JSONObject.fromObject(contentObject); 
		Value = json.toString();
		return Value;
	}
	
	/**
	 * 格式内容替换转化，下发用的
	 * @param map
	 * @param content
	 * @return
	 */
	public String changeValueProperties(Map<String,Object> map_key_outside,Map<String,Object> map,String content){
		String Value = "";
		//content未替换格式
		ContentObject contentObject = new Gson().fromJson(content, new TypeToken<ContentObject>() {}.getType());
		DownProObject downProObject = new DownProObject();

		downProObject.setType(contentObject.getType());
		if(map.containsKey("frequency")){
			downProObject.setFrequency(Integer.parseInt(map.get("frequency").toString()));
		}else{
			//写死目前只有主机
			downProObject.setFrequency(60);
		}
		downProObject.setFilename(map_key_outside.get("file_name").toString());
		
		//info
		Map<String,String> info = contentObject.getInfo();
		Set<String> info_keys =info.keySet();
		for(String info_key :info_keys){
			if(map_key_outside.get(info_key) != null){
				String key_value = map_key_outside.get(info_key).toString();   
				info.put(info_key, key_value);
			}
		}
		
		//config
		Map<String,Object> config = contentObject.getConfig();
		Set<String> config_keys =config.keySet();
		for(String config_key :config_keys){
			System.out.println(config_key);
			
			if("contentfilter".equals(config_key)){
				Map <String, Object>  contentfilterJsonTextMap = new HashMap<String, Object>();
				Map <String, Object>  contentfilterMap= (Map) config.get(config_key);
				
				Set<String> contentfilterkeys =contentfilterMap.keySet();
				for(String contentfilterkey :contentfilterkeys){
					String value = map.get(contentfilterkey).toString();
					//String[] value_array = value.split(",");
					//String[] value = commaDivider(value);	
							
					List<String> successflagList = new ArrayList<String>();
					if("successflag".equals(contentfilterkey)){
						String[] successflagArray = map.get(contentfilterkey).toString().split(",");
						List<String> sqllist =  java.util.Arrays.asList(successflagArray);
						successflagList =sqllist;
						contentfilterJsonTextMap.put(contentfilterkey, successflagList);
					}else if("columnsreg".equals(contentfilterkey)){
						value ="{"+map.get(contentfilterkey).toString()+"}";
						contentfilterJsonTextMap.put(contentfilterkey, value);
					}else if("costunit".equals(contentfilterkey) || "urlrestfullimit".equals(contentfilterkey)){
						contentfilterJsonTextMap.put(contentfilterkey, Integer.parseInt(value.trim()));
					}else if("disableurlcut".equals(contentfilterkey)){
						contentfilterJsonTextMap.put(contentfilterkey, Boolean.parseBoolean(value));
					}else if("multicolumn".equals(contentfilterkey)){
						contentfilterJsonTextMap.put(contentfilterkey, Boolean.parseBoolean(value));
					}else{
						value = map.get(contentfilterkey).toString();
						contentfilterJsonTextMap.put(contentfilterkey, value);
					}

				}						
				config.put(config_key, contentfilterJsonTextMap);
			}else if("match".equals(config_key) && "javagclog".equals(contentObject.getType())){
				Map <String, Object>  contentfilterJsonTextMap = new HashMap<String, Object>();
				Map <String, Object>  contentfilterMap= (Map) config.get(config_key);
				
				Set<String> contentfilterkeys =contentfilterMap.keySet();
				for(String contentfilterkey :contentfilterkeys){
					
					String[] matchArray = map.get(contentfilterkey).toString().split("==");
					matchArray[0] = matchArray[0].substring(1, matchArray[0].length());
					matchArray[1] = matchArray[1].substring(0, matchArray[1].length()-1);
					List<String> sqllist =  java.util.Arrays.asList(matchArray);
					contentfilterJsonTextMap.put(contentfilterkey, sqllist);
					
					//String value = map.get(contentfilterkey).toString();
					//String[] value_array = value.split(",");
					//String[] value = commaDivider(value);	
					//value = map.get(contentfilterkey).toString();
					//contentfilterJsonTextMap.put(contentfilterkey, value);
				}						
				config.put(config_key, contentfilterJsonTextMap);
			}else{		
				//;号处理
				if("sqls".equals(config_key)||"msqls".equals(config_key)){
					//sqls=select 1 as id,2 as name from dual;/nselect id from dual;
					String sqls_Str = map.get(config_key).toString();
					String[]  sqls_Array = sqls_Str.replaceAll("\n","").split(";");
					List<String> sqllist =  java.util.Arrays.asList(sqls_Array);
					//= new Gson().fromJson(map.get(config_key).toString(), new TypeToken<List<String>>() {}.getType());
					config.put(config_key, sqllist);
				//;号处理,本想通过,号处理
				}else if("logfiles".equals(config_key)){
					String sqls_Str = map.get(config_key).toString();
					String[]  sqls_Array = sqls_Str.replaceAll("\n","").split(";");
					List<String> sqllist =  java.util.Arrays.asList(sqls_Array);
					//= new Gson().fromJson(map.get(config_key).toString(), new TypeToken<List<String>>() {}.getType());
					config.put(config_key, sqllist);
				}else if("disablenamefilter".equals(config_key)){
					config.put(config_key, Boolean.parseBoolean(map.get(config_key).toString()));
				}else if("maxread".equals(config_key)){
					config.put(config_key, Integer.parseInt(map.get(config_key).toString()));
				}else{
					config.put(config_key, map.get(config_key).toString());
				}
			}
			
			if(map.get(config_key) != null){
				//更改主机true、false为布尔类型
				if("true".equals(map.get(config_key).toString())){
					config.put(config_key, true);
				}else if("false".equals(map.get(config_key).toString())){
					config.put(config_key, false);
				}
			}

		}
		//}
		downProObject.setInfo(info);
		downProObject.setConfig(config);

		
		JSONObject json = JSONObject.fromObject(downProObject); 
		Value = json.toString();
		return Value;
	}
	
	
	/**
	 * update下发接口
	 * @param id
	 * @param object_id
	 * @param json_text
	 * @return
	 */
	@RequestMapping(value="/system/updateServiceTemplet",method=RequestMethod.POST)
	public  int updateServiceTemplet(@RequestBody Map map){
		 int cnt =0;
		 String id = map.get("id").toString();
		 String object_id = map.get("object_id").toString();
		 String json_text = map.get("json_text").toString();
		 int templet_id = systemService.getTempId(Integer.valueOf(id));
		 String content = systemService.getTempContent(templet_id);
		 List<Map<String,Object>> list_properties = new Gson().fromJson(json_text, new TypeToken<List<Map<String,Object>>>() {}.getType());
		 Map map_properties_key = new HashMap();
    	 for(Map key_map:list_properties){ 
    		 map_properties_key.put(key_map.get("key_ena").toString(), key_map.get("defult_value"));
    	 }
    	 Map<String,Object> upmap =  (Map<String, Object>) map.get("update_data");
    	 Set<Entry<String, Object>> entries = upmap.entrySet();
 		for (Entry<String, Object> entry : entries) { 
 			map.put(entry.getKey(), entry.getValue());
 		}
    	 String host_name = (String) map.get("host_name");
		 String file_name = (String) map.get("indextemplateid");
		 map.put("file_name",file_name);
    	 //map_properties_key:真实值;content:格式值
    	 String Value = changeValueJson(map_properties_key,content);
    	 String Properties = changeValueProperties(map,map_properties_key,content);
		 cnt = templetService.callbackTotempletConfig(id, object_id ,Value);
		 JSONObject json_returnStr = templetService.saveAndload(host_name, file_name, "update", Properties);
		 return cnt;
	}

	
	@RequestMapping(value="/system/delServiceTemplet",method=RequestMethod.POST)
	public  int delServiceTemlate(@RequestParam(value="id", required=true) int id,@RequestParam(value="obj_id", required=true)  int obj_id){ 
         int cnt = 0;
         Map map = new HashMap();
         map.put("id", id);
         map.put("obj_id", obj_id);
         Map configMap = systemService.getServiceTempletConfig(id);
         
         //删除表中记录
         cnt += systemService.delServiceTemplet(map);
         
         //同时清理下发的文件
         String file_name = configMap.get("indextemplateid").toString();
         String host_name = configMap.get("host_name").toString();
         String flag = "del";
		 //调用agent的下发接口
		 JSONObject json_returnStr = templetService.saveAndload(host_name, file_name, flag, "");
         
        return cnt;
	}
	
	//传入的是本条记录在数据库配置模板中的记录 id
	@RequestMapping(value="/system/getIndexByServiceId",method=RequestMethod.GET)
	public  List<Map<String, Object>> getIndexByServiceId(@RequestParam(value="object_id", required=true) int object_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> indexpropertyList = new ArrayList<Map<String, Object>>();
		
		Long IndexTempId = systemService.getIndexTempId(object_id);
		
		indexpropertyList = systemService.getIndexPropertyByIndexTempId(String.valueOf(IndexTempId));

		//reslutList = systemService.getIndexByServiceId(object_id);
		return indexpropertyList; 
	}
	
	/**
	 * 获取模板属性
	 * @param templet_id
	 * @return
	 */
	@RequestMapping(value="/system/getTempProperties",method=RequestMethod.GET)
	public  List<Map<String, Object>> getTempProperties(@RequestParam(value="templet_id", required=true) int templet_id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> originList = new ArrayList<Map<String, Object>>();
		String content = systemService.getTempContent(templet_id);
//		 List<String> keyList=new ArrayList<String>();
//		if(content != ""){
//	        Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");
//	        Matcher matcher = pattern.matcher(content);
//	        while(matcher.find()){
//	        	keyList.add(matcher.group());
//	        } 
//	        reslutList = systemService.getTempProperties(keyList);
//		}
//		content = "{{\"type\" : \"host\" , \"frequency\" : “采集频率,60,Y,”,\"config\" :{\"cpu\" :”cpu,,false,”,\"mem\" : ”mem ,,false, ”,\"kernel\" : ” kernel,,false,”,\"load\" : ” load,,true,”,\"io\" : ” io,,false, ”,\"net\" : ” net ,,false, ”,\"netstat\" : ” netstat ,,false,”,\"disk\" : ”disk,,false,”, \"df\" : ” df,,false,”,},\"info\" : {\"sys_name\":\"HHHHost-ACQ\",\"indextemplateid\":\" 2312321313\",\" obj_name\":\" CNS40009\",\" host_name\":\"CNS40009\",}}";
		
		Map<String,Object> contMap = new Gson().fromJson(content, new TypeToken<Map<String,Object>>() {}.getType());
		Map<String,Object> freMap  = new HashMap<String,Object>();
		freMap.put("frequency", contMap.get("frequency").toString());
		originList.add(freMap);
		Map <String, Object>  conMap= (Map) contMap.get("config");
		//Map<String,Object> conMap = new Gson().fromJson(config, new TypeToken<Map<String,Object>>() {}.getType());
		Set<Entry<String, Object>> entries = conMap.entrySet();
		for (Entry<String, Object> entry : entries) {  
			Map<String,Object> tempMap  = new HashMap<String,Object>();
			//acclog模板
			if("contentfilter".equals(entry.getKey())){
				Map <String, Object>  filterMap = (Map<String, Object>) entry.getValue();
				//Map <String, Object>  filterMap= new Gson().fromJson(strfilter, new TypeToken<Map<String,Object>>() {}.getType());
				Set<Entry<String, Object>> sets = filterMap.entrySet();
				for (Entry<String, Object> set : sets) {
					
					Map<String,Object> setMap  = new HashMap<String,Object>();
					setMap.put(set.getKey() , set.getValue().toString());  
					originList.add(setMap);
				}
			}else if("match".equals(entry.getKey())  && "javagclog".equals(contMap.get("type"))){
				Map <String, Object>  filterMap = (Map<String, Object>) entry.getValue();
				//Map <String, Object>  filterMap= new Gson().fromJson(strfilter, new TypeToken<Map<String,Object>>() {}.getType());
				Set<Entry<String, Object>> sets = filterMap.entrySet();
				for (Entry<String, Object> set : sets) {
					
					Map<String,Object> setMap  = new HashMap<String,Object>();
					setMap.put(set.getKey() , set.getValue().toString());  
					originList.add(setMap);
				}
			}
//			else if("sqls".equals(entry.getKey())||"msqls".equals(entry.getKey())||"logfiles".equals(entry.getKey())||"successflag".equals(entry.getKey())){
//				Map <String, Object>  filterMap = (Map<String, Object>) entry.getValue();
//				//Map <String, Object>  filterMap= new Gson().fromJson(strfilter, new TypeToken<Map<String,Object>>() {}.getType());
//				Set<Entry<String, Object>> sets = filterMap.entrySet();
//				for (Entry<String, Object> set : sets) {
//					Map<String,Object> setMap  = new HashMap<String,Object>();
//					setMap.put(set.getKey() , set.getValue().toString());  
//					originList.add(setMap);
//				}
//			}
			else{
				//其他模板
				tempMap.put(entry.getKey() , entry.getValue().toString());  
				originList.add(tempMap);
			}
		}
		
//		Map <String, Object>  infoMap= (Map) contMap.get("info");
//		Set<Entry<String, Object>> info_entries = infoMap.entrySet();
//		for (Entry<String, Object> entry : info_entries) {  
//			Map<String,Object> tempMap  = new HashMap<String,Object>();
//			tempMap.put(entry.getKey() , entry.getValue().toString());  
//			originList.add(tempMap);
//		}
		
		for(Map<String, Object> orgMap : originList){
			Map<String,Object> temp  = new HashMap<String,Object>();
			Set<String> keys = orgMap.keySet();
			String[] values = null;
			for(String key :keys){
              temp.put("key_ena",key);
                    		   
              if("columns".equals(key)||"urlstaticdef".equals(key)||"columnsreg".equals(key)||"successflag".equals(key) ||"logfiles".equals(key)){
            	  String str = (String) orgMap.get(key);
            	  values = commaDivider(str);
              }else if("oc".equals(key) ||"yc".equals(key)){    //临时存储为==号，下发时候转化为,号
            	  String str = (String) orgMap.get(key);
            	  values = str.split(",");
              }
              else{
            	  String str = (String) orgMap.get(key);
                  values =  str.split(",");
              }
              if(values.length == 4){
                  temp.put("key_cna",values[0]);
                  if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)||"successflag".equals(key)){
                	  temp.put("defult_value",values[1].replace("[", "").replace("]", ""));
                  }else if("oc".equals(key) ||"yc".equals(key)){
                	  temp.put("defult_value",values[1].substring(1,values[1].length()-1));
                  }else{
                      temp.put("defult_value",values[1]); 
                  }
                  temp.put("is_req",values[2]);
                  temp.put("tip",values[3]);
              }else if(values.length == 3){
                  temp.put("key_cna",values[0]);
                  if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)||"successflag".equals(key)){
                	  temp.put("defult_value",values[1].replace("[", "").replace("]", ""));
                  }else if("oc".equals(key) ||"yc".equals(key)){
                	  temp.put("defult_value",values[1].substring(1,values[1].length()-1));
                  }else{
                      temp.put("defult_value",values[1]); 
                  }
                  temp.put("is_req",values[2]);
                  temp.put("tip","...");
              }
			}
			reslutList.add(temp);
		}
		
		
		return reslutList; 
	}
	
	
	
	/**
	 * 获取已配置模板属性值
	 * @param templet_id
	 * @return
	 */
	@RequestMapping(value="/system/getTempPropertiesValue",method=RequestMethod.GET)
	public  List<Map<String, Object>> getTempPropertiesValue(@RequestParam(value="id", required=true) int id){ 
		List<Map<String, Object>> reslutList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> originList = new ArrayList<Map<String, Object>>();
		
		String json_text = systemService.getTempJsonText(id);
	    
		Map<String,Object> contMap = new Gson().fromJson(json_text, new TypeToken<Map<String,Object>>() {}.getType());
		Map<String,Object> freMap  = new HashMap<String,Object>();
		//freMap.put("frequency", contMap.get("frequency").toString());
		if(contMap.containsKey("frequency")){
			freMap.put("frequency", contMap.get("frequency").toString());
		}
		originList.add(freMap);
		Map <String, Object>  conMap= (Map) contMap.get("config");

		Set<Entry<String, Object>> entries = conMap.entrySet();
		for (Entry<String, Object> entry : entries) {
			Map<String,Object> tempMap  = new HashMap<String,Object>();
			//acclog模板
			
			if("contentfilter".equals(entry.getKey())){
				Map <String, Object>  filterMap = (Map<String, Object>) entry.getValue();
				//Map <String, Object>  filterMap= new Gson().fromJson(strfilter, new TypeToken<Map<String,Object>>() {}.getType());
				//Map <String, Object>  filterMap= new Gson().fromJson(entry.getKey(), new TypeToken<Map<String,Object>>() {}.getType());
				Set<Entry<String, Object>> sets = filterMap.entrySet();
				for (Entry<String, Object> set : sets) {
					Map<String,Object> setMap  = new HashMap<String,Object>();
					setMap.put(set.getKey() , set.getValue().toString());  
					originList.add(setMap);
				}
			}else if("match".equals(entry.getKey()) && "javagclog".equals(contMap.get("type"))){
				Map <String, Object>  filterMap = (Map<String, Object>) entry.getValue();
				//Map <String, Object>  filterMap= new Gson().fromJson(strfilter, new TypeToken<Map<String,Object>>() {}.getType());
				//Map <String, Object>  filterMap= new Gson().fromJson(entry.getKey(), new TypeToken<Map<String,Object>>() {}.getType());
				Set<Entry<String, Object>> sets = filterMap.entrySet();
				for (Entry<String, Object> set : sets) {
					Map<String,Object> setMap  = new HashMap<String,Object>();
					setMap.put(set.getKey() , set.getValue().toString());  
					originList.add(setMap);
				}
			}else{
				//其他模板
				tempMap.put(entry.getKey() , entry.getValue().toString());  
				originList.add(tempMap);
			}
		}
		
		//map list 放好之后，开始切分出数据
		for(Map<String, Object> orgMap : originList){
			Map<String,Object> temp  = new HashMap<String,Object>();
			Set<String> keys = orgMap.keySet();
			String[] values = null;
			for(String key :keys){
              temp.put("key_ena",key);
              if("columns".equals(key)||"columnsreg".equals(key)||"urlstaticdef".equals(key)||"sqls".equals(key) ||"msqls".equals(key) ||"logfiles".equals(key)||"successflag".equals(key)){
            	  String str = (String) orgMap.get(key);
            	  values = commaDivider(str);
              }else{
            	  String str = (String) orgMap.get(key);
                  values =  str.split(",");
              }
           
              if(values.length == 4){
                  temp.put("key_cna",values[0]);
                  if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)||"successflag".equals(key)){
                	  temp.put("defult_value",values[1].replace("[", "").replace("]", ""));
                  }else if("yc".equals(key) ||"oc".equals(key)){
                	  temp.put("defult_value",values[1].substring(1,values[1].length()-1));
                  }else{
                      temp.put("defult_value",values[1]); 
                  }
                  temp.put("is_req",values[2]);
                  temp.put("tip",values[3]);
              }else if(values.length == 3){
                  temp.put("key_cna",values[0]);
                  if("sqls".equals(key)||"msqls".equals(key)||"logfiles".equals(key)||"successflag".equals(key)){
                	  temp.put("defult_value",values[1].replace("[", "").replace("]", ""));
                  }else if("yc".equals(key) ||"oc".equals(key)){
                	  temp.put("defult_value",values[1].substring(1,values[1].length()-1));
                  }else{
                      temp.put("defult_value",values[1]); 
                  }
                  temp.put("is_req",values[2]);
                  temp.put("tip","...");
              }
			}
			reslutList.add(temp);
		}
		
		return reslutList; 
	}

	   public static String [] commaDivider(String sss){
	        //双引号开始标记
	        int qutationStart =0;
	        //双引号结束标记
	        int qutationEnd =0;
	        char[] charStr = sss.toCharArray();
	        //用于拼接字符 作为一个字段值
	        StringBuffer sbf = new StringBuffer();
	        //结果list
	        List<String> list = new ArrayList<String>();
	        //逐个字符处理
	        for(int i=0;i<charStr.length;i++) {
	            //在此之前还未遇到双引号并且当前的字符为\"
	            if(qutationStart == 0&&charStr[i] == '\"') {
	                
	                qutationStart = 1;
	                qutationEnd = 0;
	                continue;
	            } else if(qutationStart == 1&&charStr[i] == '\"'){
	                //在此之前遇到了双引号并且当前的字符为\" 说明字段拼接该结束了
	                qutationStart = 0;
	                qutationEnd = 1;
	                //当最后一个字符是双引号时，由于下次循环不会执行，所以在此保存一下
	                if(i == charStr.length-1&&sbf.length() != 0) {
	                    list.add(sbf.toString());
	                    sbf.setLength(0);
	                }
	                continue;
	            } else if(qutationStart == 1&&charStr[i] == ','&&qutationEnd == 0) {
	                //处理 \"中国,北京\"这种不规范的字符串
	                sbf.append(charStr[i]);
	                continue;
	            }else if(charStr[i] == ',') {
	                list.add(sbf.toString());
	                sbf.setLength(0);
	                continue;
	            }
	            //不属于分隔符的就拼接
	            sbf.append(charStr[i]);
	            if(i == charStr.length-1&&sbf.length()!=0) {
	                list.add(sbf.toString());
	                sbf.setLength(0);
	            }
	            
	        }
	        
	        return (String[])list.toArray(new String[list.size()]);
	    }	
	
}
